'use strict';

const Controller = require('egg').Controller;

class ClothingController extends Controller {
  // 获取衣服列表
  async index() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1; // 临时使用演示用户ID
    
    const query = ctx.query;
    const options = {
      page: parseInt(query.page) || 1,
      pageSize: parseInt(query.pageSize) || 20,
      category_id: query.category_id,
      color: query.color,
      season: query.season,
      style: query.style,
      status: query.status,
      keyword: query.keyword,
      is_favorite: query.is_favorite,
    };

    try {
      const result = await service.clothing.getList(userId, options);
      
      ctx.body = {
        code: 200,
        message: '获取成功',
        data: result,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取衣服详情
  async show() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const clothingId = ctx.params.id;

    try {
      const clothing = await service.clothing.findById(clothingId, userId);
      if (!clothing) {
        ctx.throw(404, '衣服不存在');
      }

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: clothing,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 创建衣服
  async create() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;

    // 参数验证
    ctx.validate({
      name: { type: 'string', required: true, max: 100 },
      category_id: { type: 'int', required: true },
      brand: { type: 'string', required: false, max: 50 },
      color: { type: 'string', required: false, max: 30 },
      size: { type: 'string', required: false, max: 20 },
      material: { type: 'string', required: false, max: 100 },
      price: { type: 'number', required: false, min: 0 },
      season: { type: 'enum', values: ['spring', 'summer', 'autumn', 'winter', 'all'], required: false },
      style: { type: 'enum', values: ['casual', 'formal', 'business', 'sport', 'party', 'vintage', 'street'], required: false },
    });

    try {
      const clothingData = {
        ...ctx.request.body,
        user_id: userId,
      };

      const clothing = await service.clothing.create(clothingData);

      ctx.body = {
        code: 200,
        message: '创建成功',
        data: clothing,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 更新衣服
  async update() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const clothingId = ctx.params.id;

    try {
      // 检查衣服是否存在且属于当前用户
      const clothing = await service.clothing.findById(clothingId, userId);
      if (!clothing) {
        ctx.throw(404, '衣服不存在');
      }

      const updateData = ctx.request.body;
      await service.clothing.updateById(clothingId, updateData);

      ctx.body = {
        code: 200,
        message: '更新成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 删除衣服
  async destroy() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const clothingId = ctx.params.id;

    try {
      // 检查衣服是否存在且属于当前用户
      const clothing = await service.clothing.findById(clothingId, userId);
      if (!clothing) {
        ctx.throw(404, '衣服不存在');
      }

      await service.clothing.deleteById(clothingId);

      ctx.body = {
        code: 200,
        message: '删除成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 上传衣服图片
  async uploadImages() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const clothingId = ctx.params.id;

    try {
      // 检查衣服是否存在且属于当前用户
      const clothing = await service.clothing.findById(clothingId, userId);
      if (!clothing) {
        ctx.throw(404, '衣服不存在');
      }

      const files = ctx.request.files;
      if (!files || files.length === 0) {
        ctx.throw(400, '请选择文件');
      }

      // 上传图片
      const imageUrls = [];
      for (const file of files) {
        const imageUrl = await service.upload.uploadImage(file, 'clothing');
        imageUrls.push(imageUrl);
      }

      // 更新衣服图片
      const currentImages = clothing.images || [];
      const newImages = [...currentImages, ...imageUrls];
      
      await service.clothing.updateById(clothingId, {
        images: newImages,
        main_image: clothing.main_image || imageUrls[0],
      });

      ctx.body = {
        code: 200,
        message: '图片上传成功',
        data: {
          images: imageUrls,
        },
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 设置主图片
  async setMainImage() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const clothingId = ctx.params.id;

    ctx.validate({
      imageUrl: { type: 'string', required: true },
    });

    try {
      const clothing = await service.clothing.findById(clothingId, userId);
      if (!clothing) {
        ctx.throw(404, '衣服不存在');
      }

      const { imageUrl } = ctx.request.body;
      
      // 检查图片是否在衣服的图片列表中
      if (!clothing.images || !clothing.images.includes(imageUrl)) {
        ctx.throw(400, '图片不存在');
      }

      await service.clothing.updateById(clothingId, {
        main_image: imageUrl,
      });

      ctx.body = {
        code: 200,
        message: '主图片设置成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 收藏/取消收藏衣服
  async toggleFavorite() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const clothingId = ctx.params.id;

    try {
      const clothing = await service.clothing.findById(clothingId, userId);
      if (!clothing) {
        ctx.throw(404, '衣服不存在');
      }

      const isFavorite = !clothing.is_favorite;
      await service.clothing.updateById(clothingId, {
        is_favorite: isFavorite,
      });

      ctx.body = {
        code: 200,
        message: isFavorite ? '收藏成功' : '取消收藏成功',
        data: {
          is_favorite: isFavorite,
        },
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 更新衣服状态
  async updateStatus() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const clothingId = ctx.params.id;

    ctx.validate({
      status: { type: 'enum', values: ['available', 'wearing', 'washing', 'dry_cleaning', 'damaged', 'donated'], required: true },
    });

    try {
      const clothing = await service.clothing.findById(clothingId, userId);
      if (!clothing) {
        ctx.throw(404, '衣服不存在');
      }

      const { status } = ctx.request.body;
      await service.clothing.updateById(clothingId, { status });

      ctx.body = {
        code: 200,
        message: '状态更新成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }
}

module.exports = ClothingController;
